package com.example.mystore.controller;



import com.example.mystore.model.Order;
import com.example.mystore.model.OrderDao;
import com.example.mystore.model.User;
import com.example.mystore.model.OrderRequest;
import com.example.mystore.model.dto.OrderDto;
import com.example.mystore.service.OrderService;
import com.example.mystore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @PostMapping()
    public ResponseEntity<String> confirmOrder(@RequestBody OrderRequest orderRequest) {
        try {
            orderService.createOrder(orderRequest);
            return ResponseEntity.ok("订单确认成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("订单确认失败，请重试！");
        }
    }

    @DeleteMapping("/{id}")
    public int deleteOrderById(@PathVariable int id) {
        return orderService.deleteOrderById(id);
    }

    @PutMapping
    public int updateOrder(@RequestBody Order order) {
        return orderService.updateOrder(order);
    }

    @GetMapping("/order/{userId}")
    public List<Order> getOrderById(@PathVariable Integer userId) {
        return orderService.getOrderById(userId);
    }

    @GetMapping("/orderNo/{orderNo}")
    public Order getOrderByNo(@PathVariable int orderNo) {
        return orderService.getOrderByNo(orderNo);
    }

    @GetMapping
    public List<Order> getAllOrders() {
        return orderService.getAllOrders();
    }

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable int id) {
        return userService.getUserById(id);
    }

    @GetMapping("/{orderNo}")
    public ResponseEntity<OrderDao> getOrderDetails(@PathVariable("orderNo") Integer orderNo) {
        OrderDao orderDetailsDTO = orderService.getOrderDetails(orderNo);
        if (orderDetailsDTO != null) {
            return ResponseEntity.ok(orderDetailsDTO);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("detail")
    public ResponseEntity<OrderDto> getOrderDetail(Integer id) {
        return ResponseEntity.ok(orderService.getOrderDetail(id));
    }


}
